﻿using System;
using System.IO;
using System.IO.Compression;
using System.Web;

namespace MVC_basic.Helpers
{
    public class UnZipper
    {
        public static void unzip(ZipArchive file, string appname)
        {

            foreach (ZipArchiveEntry entry in file.Entries)
            {
                int parentFolderLength = createAppFolder(file, appname);

                if (entry.FullName.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".js", StringComparison.OrdinalIgnoreCase)
                    || entry.FullName.EndsWith(".css", StringComparison.OrdinalIgnoreCase))
                {
                    string filename = entry.FullName.Substring(parentFolderLength);
                    var path = HttpContext.Current.Server.MapPath("~/CajaApps") + "/" + appname + filename;
                    entry.ExtractToFile(path, true);
                }
            }
        }
        private static int createAppFolder(ZipArchive file, string appname)
        {
            string temp = file.Entries[0].FullName;
            string[] parent = temp.Split(new char[] { '/' });
            string subPath = "~/CajaApps/" + appname;
            bool IsExists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(subPath));
            if (!IsExists)
                System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(subPath));
            return parent.Length+1; 
        }
    }
}
